import { defineStore } from 'pinia'
import { ref } from 'vue'
import DCYX_WORD_BOOK_API, {
  type WordBookItem,
  type ProgramItem,
  type UnitItem,
  type WordListQueryParams,
  type ProgramListQueryParams,
  type UnitListQueryParams,
} from '@/api/dcyx/word-book.api'
import { store } from '@/store'

export const useDcyxWordBookStore = defineStore('dcyx_word_book', () => {
  // 状态
  const wordList = ref<WordBookItem[]>([])
  const programList = ref<ProgramItem[]>([])
  const unitList = ref<UnitItem[]>([])
  const loading = ref(false)
  const wordTotal = ref(0)
  const programTotal = ref(0)
  const unitTotal = ref(0)

  /**
   * 获取单词列表
   * @param params 查询参数
   * @returns Promise<WordBookItem[]>
   */
  function fetchWordList(params: WordListQueryParams) {
    return new Promise<WordBookItem[]>((resolve, reject) => {
      loading.value = true
      DCYX_WORD_BOOK_API.getWordList(params)
        .then((res) => {
          // 为每个单词添加序号
          console.log(res)
          const wordsWithIndex = res.list.map((word, index) => ({
            ...word,
            wordIndex: (params.pageNum - 1) * params.pageSize + index + 1,
          }))
          wordList.value = wordsWithIndex
          wordTotal.value = res.total
          resolve(wordsWithIndex)
        })
        .catch((error) => {
          wordList.value = []
          wordTotal.value = 0
          reject(error)
        })
        .finally(() => {
          loading.value = false
        })
    })
  }

  /**
   * 获取教材列表
   * @param params 查询参数
   * @returns Promise<ProgramItem[]>
   */
  function fetchProgramList(params: ProgramListQueryParams) {
    return new Promise<ProgramItem[]>((resolve, reject) => {
      DCYX_WORD_BOOK_API.getProgramList(params)
        .then((res) => {
          programList.value = res.list
          programTotal.value = res.total
          resolve(res.list)
        })
        .catch((error) => {
          programList.value = []
          programTotal.value = 0
          reject(error)
        })
    })
  }

  /**
   * 获取单元列表
   * @param params 查询参数
   * @returns Promise<UnitItem[]>
   */
  function fetchUnitList(params: UnitListQueryParams) {
    return new Promise<UnitItem[]>((resolve, reject) => {
      DCYX_WORD_BOOK_API.getUnitList(params)
        .then((res) => {
          unitList.value = res.list
          unitTotal.value = res.total
          resolve(res.list)
        })
        .catch((error) => {
          unitList.value = []
          unitTotal.value = 0
          reject(error)
        })
    })
  }

  // 播放单词音频，返回 blob url
  const playWordAudio = async (word: string): Promise<string> => {
    const blob = await DCYX_WORD_BOOK_API.getWordAudio(word)
    // 兼容 axios 返回 {data: Blob} 或直接 Blob
    const realBlob = blob instanceof Blob ? blob : blob.data
    return URL.createObjectURL(realBlob)
  }

  /**
   * 播放单词音频
   * @param word 单词
   * @returns Promise<void>
   */
  // function playWordAudio(word: string) {
  //   return new Promise<void>((resolve, reject) => {
  //     DCYX_WORD_BOOK_API.getWordAudio(word)
  //       .then((audioBlob) => {
  //         const audioUrl = URL.createObjectURL(audioBlob)
  //         const audio = new Audio(audioUrl)

  //         audio.onended = () => {
  //           URL.revokeObjectURL(audioUrl)
  //           resolve()
  //         }

  //         audio.onerror = () => {
  //           URL.revokeObjectURL(audioUrl)
  //           reject(new Error('音频播放失败'))
  //         }

  //         audio.play().catch(reject)
  //       })
  //       .catch(reject)
  //   })
  // }

  /**
   * 重置单词本状态
   */
  function resetWordBookStore() {
    wordList.value = []
    programList.value = []
    unitList.value = []
    wordTotal.value = 0
    programTotal.value = 0
    unitTotal.value = 0
    loading.value = false
  }

  return {
    // 状态
    wordList,
    programList,
    unitList,
    loading,
    wordTotal,
    programTotal,
    unitTotal,

    // 方法
    fetchWordList,
    fetchProgramList,
    fetchUnitList,
    playWordAudio,
    resetWordBookStore,
  }
})

export function useDcyxWordBookStoreHook() {
  return useDcyxWordBookStore(store)
}
